using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Collections;
using System.Reflection;

using ComLib.Configuration;
using ComLib.Data;
using ComLib.Web.Modules.Services;
using ComLib.Web.Modules.Settings;
using ComLib.Web.Lib.Controllers;
using ComLib.Web.Lib.Models;



namespace ComLib.CMS.Areas.Admin
{
    [Authorize(Roles = "Admin")]
    public class ConfigController : Controller
    {

        public ConfigController()
        {
            ModelBinders.Binders[typeof(IConfigSourceDynamic)] = new DefaultModelBinder();
        }


        /// <summary>
        /// Edit
        /// </summary>
        /// <returns></returns>
        public ViewResult Edit()
        {
            var config = GetSettings();
            return View("Edit", config);
        }


        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Save(FormCollection form)
        {
            var config = GetSettings();
            IDictionary<string, string> excludeProps = null;
            if (config.Config is Configuration.ConfigSourceDynamic)
                excludeProps = ((Configuration.ConfigSourceDynamic)config.Config).ExcludedProps;
            MapperSupport.MapperWebForms.UpdateModel(config.Config, this.Request.Form, "Config", excludeProps);
            config.Config.Save();
            return View("Edit", config) ;
        }


        private ConfigViewModel GetSettings()
        {
            string configName = this.Request.Params["configname"];
            if (string.IsNullOrEmpty(configName))
                configName = this.Request.Form["confignameInForm"];

            var config = Dashboard.Configs[configName] as IConfigSourceDynamic;
            return new ConfigViewModel(configName, config);
        }
    }



    public class ConfigViewModel
    {
        public string Name;
        public IConfigSourceDynamic Config;


        public ConfigViewModel(string name, IConfigSourceDynamic config)
        {
            Name = name;
            Config = config;
        }
    }
}
